package com.dsit.sq.protocol;


import com.google.gson.Gson;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import protocol.CircularByteBuffer;

/**
 * Created by Administrator on 2016/9/12.
 */
public class ProtoMsg {
    String TAG = "ProtoMsg";
    public String action;
    public String content;
    int headIndex = 0;
    int msgLen = 0;
    Gson gson = new Gson();
    CircularByteBuffer cbuf;

    public interface ProtoMsgListener{
        void onProtolMessageReceive(ProtoMsg msg);
    }

    ProtoMsgListener listener;


    public ProtoMsg(){

    }

    public ProtoMsg(String act, String content){
        this.action = act;
        this.content = content;
    }

    public void setListener(ProtoMsgListener listener){
        this.listener = listener;
    }

    public void setBuffer(CircularByteBuffer buffer){
        this.cbuf = buffer;
    }

    public String toString(){
        return "[action="+action
                + ",contentBytesLen="+content.getBytes().length
                + ",content="+content+"]";
    }

    public static String toJsonString(ProtoMsg msg){
        Gson gson = new Gson();
        return gson.toJson(msg);
    }

    public  String toJsonString(){
        Gson gson = new Gson();
        return gson.toJson(this);
    }

    public static ProtoMsg fromJson(String str){
        Gson gson = new Gson();
        return  gson.fromJson(str,ProtoMsg.class);
    }

    public  byte[] toBytes(){
        String content = toJsonString(this);
        int length = content.getBytes().length; // 消息长度
        ByteBuffer byteBuffer = ByteBuffer.allocate(length + 2 + 4); // head | len | data
        byteBuffer.order(ByteOrder.nativeOrder());
        byteBuffer.put((byte) 0x55);
        byteBuffer.put((byte) 0xAA);
        byteBuffer.putInt(length); // len of content bytes
        byteBuffer.put(content.getBytes());// data bytes
        return byteBuffer.array();
    }

    public void readData(byte[] data, int len){
        if(cbuf==null){
            throw new NullPointerException("cbuf==null");
        }

        cbuf.WriteArray(data, len);
        while ((headIndex = cbuf.IndexOf((byte)0x55, (byte)0xAA)) != -1)
        {
            msgLen = cbuf.getInt32(headIndex, 2) + 4;
            if (msgLen > cbuf.ReadableBytes())// 断包
            {
                break;
            }

            byte[] msgObj = new byte[msgLen];
            cbuf.ReadArray(msgLen, msgObj);
//            Log.i(TAG,"=======> "+Utils.bytes2HexString(msgObj,msgLen));
            if(listener!=null){
                String jstring = new String(msgObj,0,msgLen);
                listener.onProtolMessageReceive(gson.fromJson(jstring,ProtoMsg.class));
            }
        }
    }
}
